package com.flot.yazb.home.splash;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.Toast;

import com.flot.yazb.R;
import com.flot.yazb.base.BApplication;
import com.flot.yazb.ChannelManage;
import com.flot.yazb.SPKeyConfig;
import com.flot.yazb.base.model.BModel;
import com.flot.yazb.aop.stub.CodeStub;
import com.flot.yazb.base.BActivity;
import com.flot.yazb.model.user.RegistModel;
import com.flot.yazb.model.user.UserModel;
import com.flot.yazb.home.HomeActivity;
import com.flot.yazb.widget.utils.SharedPreferencesUtils;
import com.flot.yazb.widget.utils.StatusBarUtils;
import com.flot.yazb.widget.utils.ToastUtil;
import com.flot.yazb.widget.update.AppUpdateProgressDialog;

import java.io.File;

import butterknife.ButterKnife;

public class SplashActivity extends BActivity {
    private AppUpdateProgressDialog dialog = null;
    private int mProgress = 0;//下载进度
    private int mMaxProgress;//百分比

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        ButterKnife.bind(this);
        getAPI();
    }



    /**
     * 获取中转域名
     */
    private void getAPI() {
        startMain();
    }

    /**
     * 检查版本号
     */
    private void checkVersion() {
        showDialog();
    }

    //  2017/9/14 版本号获取与下载app
    private void showDialog() {
        mMaxProgress = 100;
        mProgress = 0;
        dialog = new AppUpdateProgressDialog(this);
        //正在下载时，不可关闭dialog
        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    Toast.makeText(SplashActivity.this, "正在下载请稍后", Toast.LENGTH_SHORT).show();
                    return true;
                } else {
                    return false;
                }
            }
        });
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mProgress < mMaxProgress) {
                    try {
                        mProgress++;
                        Message msg = myHandler.obtainMessage();
                        msg.what = 100;
                        msg.obj = mProgress;
                        myHandler.sendMessage(msg);
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    Handler myHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 100:
                    int progress = (int) msg.obj;
                    dialog.setProgress(progress);
                    if (100 == progress) {
                        dialog.dismiss();
                        String saveFileName = SplashActivity.this.getExternalCacheDir().getPath() + "/app/yazb.apk";
                        installApk(saveFileName);
                        Toast.makeText(SplashActivity.this, "下载完成，跳转到安装界面", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        StatusBarUtils.setStatusBarTranslucent(this, true, R.color.theme_color, true);
        setScreenFullToggle();
    }

    /**
     * 进入主界面
     */

    private void startMain() {
        if ("".equals(SharedPreferencesUtils.getString(this, SPKeyConfig.USERID, ""))) {
            regist();
        } else {
            getUserMsg();
        }
    }

    /**
     * 获取用户信息
     */
    private void getUserMsg() {
        String id =SharedPreferencesUtils.getString(this, SPKeyConfig.USERID, "");
        UserModel.getUserMsg(id, new BModel.Transit<UserModel>(this) {
            @Override
            public void onBorn(UserModel serializable, String code, String message) {
                if (code.equals(CodeStub.B_OK)) {
//                    serializable.id="248";
                    BApplication.getInstance().setUserModel(serializable);
                    SharedPreferencesUtils.saveString(activity, SPKeyConfig.USERID, serializable.id);
                    Intent intent = new Intent(SplashActivity.this, HomeActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    ToastUtil.showToast(activity, message);
                }
            }
        });
    }

    /**
     * 注册完成后获取用户信息
     */
    public void regist() {
        RegistModel.regist(new BModel.Transit<RegistModel>(this) {
            @Override
            public void onBorn(final RegistModel serializable, final String code, final String message) {

                if (code.equals(CodeStub.B_OK)) {
                    SharedPreferencesUtils.saveString(activity, SPKeyConfig.USERID, serializable.userid);
                    getUserMsg();
                    getInstall(ChannelManage.getChannel(SplashActivity.this));
                } else {
                    ToastUtil.showToast(activity, message);
                }

            }
        });
    }


    private void getInstall(String id) {
        BModel.getInstall(id, new BModel.Transit<BModel>(this) {
            @Override
            public void onBorn(BModel serializable, String code, String message) {

            }
        });
    }

    public void setScreenFullToggle() {

        int flag = activity.getWindow().getAttributes().flags;
        if ((flag & WindowManager.LayoutParams.FLAG_FULLSCREEN)
                == WindowManager.LayoutParams.FLAG_FULLSCREEN) {
            this.getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        } else {
            this.getWindow().setFlags(
                    WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }
    }

    /**
     * 安装apk
     */
    private void installApk(String saveFileName) {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            data = FileProvider.getUriForFile(this, "com.chexiang.myhome.android.fileprovider", apkfile);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(apkfile);
        }
        i.setDataAndType(data, "application/vnd.android.package-archive");
        startActivity(i);
    }
}
